local assets =
{
    Asset("ANIM", "anim/bboy_ghostfire.zip"),
}

local function Task(inst)
    if TheWorld:HasTag("cave") then
        return
    else
        local phase = TheWorld.state.phase
        if phase == "day" then
            inst.AnimState:PlayAnimation("post")
            inst:ListenForEvent("animover", function()
                if inst:IsValid() then
                    inst:Remove()
                end
            end)
        end
    end
end

local function ondropped(inst)
    inst.components.workable:SetWorkLeft(1)
    inst.Light:Enable(true)
    inst:DoTaskInTime(1, Task)
    inst:WatchWorldState("phase", Task)
end

local function onpickup(inst)
    inst.Light:Enable(false)
    inst:StopWatchingWorldState("phase", Task)
end

local function onworked(inst, worker)
    -- 检查工作工具是否是专属捕虫网
    if worker.components.inventory ~= nil and worker.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS) ~= nil then
        local tool = worker.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS)
        if tool.prefab == "thulecitebugnet" then
            worker.components.inventory:GiveItem(inst, nil, inst:GetPosition())
        else
            inst.components.workable:SetWorkLeft(1)
        end
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddPhysics()
    inst.entity:AddLight()
    inst.entity:AddNetwork()

    inst.Light:SetFalloff(1)
    inst.Light:SetIntensity(0.5)
    inst.Light:SetRadius(1)
    inst.Light:SetColour(0 / 255, 197 / 255, 205 / 255)
    inst.Light:Enable(true)

    inst.AnimState:SetBloomEffectHandle("shaders/anim.ksh")

    inst.AnimState:SetBank("bboy_ghostfire")
    inst.AnimState:SetBuild("bboy_ghostfire")
    inst.AnimState:PlayAnimation("pre")
    inst.AnimState:PushAnimation("idle_loop", true)

    inst.Transform:SetScale(0.5, 0.5, 1)

    inst:AddTag("NOBLOCK") -- 无障碍
    inst:AddTag("bboy_ghostfire")

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("inspectable")

    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.NET)
    inst.components.workable:SetWorkLeft(1)
    inst.components.workable:SetOnFinishCallback(onworked)

    -- 降san光环
    inst:AddComponent("sanityaura")
    inst.components.sanityaura.aura = -1/480

    inst:AddComponent("stackable")
    inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM
    inst.components.stackable.forcedropsingle = true -- 快捷丢弃只丢一个

    inst:AddComponent("inventoryitem")
    inst.components.inventoryitem:SetOnDroppedFn(ondropped)
    inst.components.inventoryitem:SetOnPickupFn(onpickup)
    inst.components.inventoryitem.canbepickedup = false
    inst.components.inventoryitem.canbepickedupalive = true

    inst:WatchWorldState("phase", Task)
    Task(inst)

    return inst
end

return Prefab("bboy_ghostfire", fn, assets)
